#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys, os, re, string
import pygtk, glib, gtk, gtk.glade, pango, pynotify
import osd
import info
from music import *
import battery_tray

pygtk.require("2.0")

reload(sys)
sys.setdefaultencoding('utf8')

class monitor_window:
    def on_time_event(self):
        text_tmp = ''
        if '--kernel' in self.argv:
            '''kernel info'''
            text_tmp += 'Kernel: %s\n' % self.info.version()

        if '--cpu' in self.argv:
            '''cpu info'''
            text_tmp += 'CPU   :%5.1f %%\n' % self.info.cpu()

        if '--memory' in self.argv:
            '''memory info'''
            text_tmp += 'MEM   :%5.1f %%\n' % self.info.mem()

        if ('--down' in self.argv) or ('--Up' in sys.argv):
            net_tmp = self.info.net()
            if '--down' in self.argv:
                '''net down info'''
                text_tmp += 'Down  :%s\n' % net_tmp[0]
            if '--up' in self.argv:
                '''net up info'''
                text_tmp += 'Up    :%s\n' % net_tmp[1]

#        if '--battery' in self.argv:
#            '''battery info'''
#            if text_tmp != '':
#                text_tmp += ' | '
#            text_tmp += 'BAT:%5.1f %%' % self.info.battery()
#

        if '--music' in self.argv:
            music_tmp = music()
            if music_tmp == ('NULL', 'NULL'):
                pass
            else:
                text_tmp += '\nMusic:%s\n%s' % music()
        #self.label.set_text('.:'+text_tmp)
        self.window.popup("<span weight='bold'>%s</span>" % text_tmp,
                        "monospace 24",
                        "#ffffff",
                        "#D7DF01")
        self.window.move()

        glib.timeout_add(1000,self.on_time_event)

    def argv_handle(self):
        pass
        #for usage in self.usage:
        #    if usage in self.argv:
        #        self.info_usage.append(usage)

    def __init__(self, argv):
        self.usage = [  '--kernel'  ,
                        '--cpu'     ,
                        '--memory'  ,
                        '--down'    ,
                        '--up'      ,
                        '--battery' ,
                        '--music'   ]
        self.argv = argv
        self.leave_enter = 'leave'
        self.argv_handle()
        self.info = info.info()

        self.window = osd.osd("a",
                            "sans serif 18",
                            "#ffffff",
                            "#000000")
        #self.window.set_opacity(0.5)
        self.window.win.stick()
        #self.window.move()

        self.on_time_event()

class battery:
    def __init__(self):
        self.battery_design     = 0
        self.battery_last_full  = 0
        self.battery_remain     = 0
        self.ac_info            = ''
        self.ac_info_tmp        = ''
        self.ac_init            = 0
        self.percent            = 0
        self.get_info()

    def get_info(self):
        battery_full_file   = open('/proc/acpi/battery/BAT0/info')
        battery_remain_file = open('/proc/acpi/battery/BAT0/state')
        ac_file             = open('/proc/acpi/ac_adapter/AC/state')
        tmp = battery_full_file.read()
        self.battery_design     = string.atof(re.compile('design capacity:\s+(\d+)').search(tmp).group(1))
        self.battery_last_full  = string.atof(re.compile('last full capacity:\s+(\d+)').search(tmp).group(1))
        self.battery_remain     = string.atof(re.compile('remaining capacity:\s+(\d+)').search(battery_remain_file.read()).group(1))
        self.ac_info = ac_file.read().split(' ')[-1]
        self.ac_info = self.ac_info[:len(self.ac_info)-1]
        battery_full_file.close()
        battery_remain_file.close()
        ac_file.close()
        self.percent = self.battery_remain*100/(self.battery_design if self.battery_remain == self.battery_design else self.battery_last_full)

    def get_tray_tooltip(self):
        self.get_info()
        return '供电方式:%s  剩余电量:%5.1f%%' % (
        '电源' if self.ac_info == 'on-line' else '电池',
        self.battery_remain*100/(self.battery_design if self.battery_remain == self.battery_design else self.battery_last_full)
        )

class window:
    def on_time_event(self):
        self.show_change()
        glib.timeout_add(1000,self.on_time_event)

    def on_percent_spinbutton_value_changed(self, widget):\
        self.wTree.get_widget('percent_hscale').set_value(int(self.wTree.get_widget('percent_spinbutton').get_value()))

    def on_percent_hscale_value_changed(self, widget):
        self.wTree.get_widget('percent_spinbutton').set_value(int(self.wTree.get_widget('percent_hscale').get_value()))

    def show_change(self):
        self.wTree.get_widget('pattern_label').set_text('电源' if battery.ac_info == 'on-line' else '电池')
        self.wTree.get_widget('percent_label').set_text('%5.1f%%' % battery.percent)
        self.wTree.get_widget('design_label').set_text('%dmAh' % battery.battery_design)
        self.wTree.get_widget('full_label').set_text('%dmAh' % battery.battery_last_full)
        self.wTree.get_widget('remain_label').set_text('%dmAh' % battery.battery_remain)

    def on_close_button_clicked(self, widget):
        print 'close'
        self.window.destroy()

    def on_ok_button_clicked(self, widget):
        info.low_percent = int(self.wTree.get_widget('percent_spinbutton').get_value())
        info.low_message = self.textview_buf.get_text(self.textview_buf.get_start_iter(), self.textview_buf.get_end_iter())
        config_file = open(info.config_path, 'w')
        config_file.write('%d\n%s' % (info.low_percent, info.low_message))
        config_file.close()
        print info.low_percent
        print info.low_message
        info.low_init = 0
        self.window.destroy()

    def __init__(self):
        self.wTree = gtk.glade.XML('ui_battery_tray.glade')
        self.window = self.wTree.get_widget('window')
        self.textview_buf = gtk.TextBuffer()
        self.wTree.get_widget('textview').set_buffer(self.textview_buf)
        self.window.show()
        self.show_change()
        self.wTree.get_widget('percent_spinbutton').set_value(info.low_percent)
        self.wTree.get_widget('percent_hscale').set_value(info.low_percent)
        self.textview_buf.set_text(info.low_message)

        self.wTree.get_widget('close_button').connect('clicked', self.on_close_button_clicked)
        self.wTree.get_widget('ok_button').connect('clicked', self.on_ok_button_clicked)
        self.wTree.get_widget('percent_spinbutton').connect('value_changed', self.on_percent_spinbutton_value_changed)
        self.wTree.get_widget('percent_hscale').connect('value_changed', self.on_percent_hscale_value_changed)

        self.on_time_event()


class tray:
    def on_activate(self, data):
        print 'active'

    def on_popup_menu(self, status, button, time):
        print 'popup menu'
        self.menu.popup(None, None, None, button, time)

    def on_preferences(self, data):
        print 'on_preferences'
        w = window()

    def on_time_event(self):
        self.tr.set_tooltip(battery.get_tray_tooltip())
        if info.low_init == 0 and battery.percent <= info.low_percent:
            pynotify.init ("low")
            low_notify = pynotify.Notification('低电警报', '电量不足%d%%\n%s' % (info.low_percent,info.low_message))
            low_notify.attach_to_status_icon(self.tr)
            low_notify.show()
            info.low_init = 1
        elif info.low_init == 0 and battery.percent > info.low_percent:
            info.low_init = 0

        if battery.ac_info != battery.ac_info_tmp and battery.ac_info == 'off-line':
            battery.ac_init = -1
            battery.ac_info_tmp = battery.ac_info
        elif battery.ac_info != battery.ac_info_tmp and battery.ac_info == 'on-line':
            battery.ac_init = 1
            battery.ac_info_tmp = battery.ac_info
        else:
            battery.ac_info_tmp = battery.ac_info
            battery.ac_init = 0

        if battery.ac_info == 'off-line' and battery.ac_init == -1:
            pynotify.init ("ac_off")
            off_notify = pynotify.Notification('供电方式', '使用电池供电')
            off_notify.attach_to_status_icon(self.tr)
            off_notify.show()
            battery.ac_init = 0
        elif battery.ac_info == 'on-line' and battery.ac_init == 1:
            pynotify.init ("ac_on")
            on_notify = pynotify.Notification('供电方式', '使用电源供电')
            on_notify.attach_to_status_icon(self.tr)
            on_notify.show()
            battery.ac_init = 0

        glib.timeout_add(1000,self.on_time_event)

    def __init__(self):
        self.tr = gtk.StatusIcon()
        self.tr.set_from_file("battery_tray.png")
        self.tr.set_tooltip(battery.get_tray_tooltip())
        self.tr.set_visible(True)

        self.preferences    = gtk.ImageMenuItem(gtk.STOCK_PREFERENCES)
        self.quit           = gtk.ImageMenuItem(gtk.STOCK_QUIT)
        self.menu           = gtk.Menu()
        for item in [self.preferences,gtk.SeparatorMenuItem(), self.quit]:
            self.menu.append(item)
        self.menu.show_all()

        self.tr.connect('activate', self.on_activate)
        self.tr.connect('popup-menu', self.on_popup_menu)
        self.quit.connect('activate', gtk.main_quit)
        self.preferences.connect('activate', self.on_preferences)

        self.on_time_event()

if __name__ == "__main__":
    if len(sys.argv) == 1:
        monitor_window(['--kernel'  ,
                        '--cpu'     ,
                        '--memory'  ,
                        '--down'    ,
                        '--up'      ,
                        '--battery' ,
                        '--music'   ])
        info = battery_tray.battery_info()
        battery = battery()
        tray()
    else:
        monitor_window(sys.argv)

    if '--battery' in sys.argv:
        info = battery_tray.battery_info()
        battery = battery()
        tray()

    gtk.main()
